﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.Identity;
using Caltech.Models;
using CaltechSoft.Service.EntityFW.Entity;
using CaltechSoft.Service.Repositories;
using AutoMapper;

namespace Caltech
{
    [HubName("userActivityHub")]
    public class UserActivityHub : Hub
    {
        /// <summary>
        /// The count of users connected.
        /// </summary>
        public static List<UserHistoryModel> Users = new List<UserHistoryModel>();

        private IUserHistoryRepository m_HistoryRepository;

        public UserActivityHub()
        {
            m_HistoryRepository = new UserHistoryRepository();
        }

        /// <summary>
        /// Sends the update user count to the listening view.
        /// </summary>
        /// <param name="count">
        /// The count.
        /// </param>
        public void Send(UserHistoryModel client)
        {
            // Call the addNewMessageToPage method to update clients.
            var context = GlobalHost.ConnectionManager.GetHubContext<UserActivityHub>();
            context.Clients.All.updateUsersOnlineCount(client);
        }

        /// <summary>
        /// Get online users
        /// </summary>
        /// <returns></returns>
        public List<UserHistoryModel> GetOnlineUsers()
        {
            return Users;
        }

        /// <summary>
        /// The OnConnected event.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public override Task OnConnected()
        {
            UserHistoryModel user = GetClientId();

            var userHistory = Users.Where(x => x.UserId == user.UserId).FirstOrDefault();
            user.Ip = HttpContext.Current.Request.UserHostAddress;
            if (userHistory == null)
            {
                var obj = Mapper.Map<UserHistory>(user);
                m_HistoryRepository.Add(obj);

                Users.Add(user);
                Send(user);
            }

            return base.OnConnected();
        }

        /// <summary>
        /// The OnReconnected event.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public override Task OnReconnected()
        {
           UserHistoryModel user = GetClientId();
            var userHistory = Users.Where(x => x.UserId == user.UserId).FirstOrDefault();

            if (userHistory == null)
            {
                var obj = Mapper.Map<UserHistory>(user);
                m_HistoryRepository.Add(obj);

                Users.Add(user);
                Send(user);
            }

            return base.OnReconnected();
        }

        /// <summary>
        /// The OnDisconnected event.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public override Task OnDisconnected(bool stopCalled)
        {
          UserHistoryModel user = GetClientId();

            var userHistory = Users.Where(x => x.UserId == user.UserId).FirstOrDefault();
            if (userHistory != null)
            {
                Users.RemoveAll(item => item.UserId == user.UserId);
                Send(user);
            }

            // Send the current count of users

            return base.OnDisconnected(stopCalled);
        }


        /// <summary>
        /// Get's the currently connected Id of the client.
        /// This is unique for each client and is used to identify
        /// a connection.
        /// </summary>
        /// <returns>The client Id.</returns>
        private UserHistoryModel GetClientId()
        {
            var user = this.Context.User.Identity;
            var account = new UserHistoryModel()
            {
                UserId = user.GetUserId(),
                LoginDate = DateTime.Now
            };
            return account;
        }
    }
}